package org.bonorsoft.modules.control.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.control.entity.*;
import org.bonorsoft.modules.control.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.modules.control.util.PoliceImportUtil;
import org.bonorsoft.modules.control.vo.PopulationVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 实有房屋信息
 * @Author: WilliamYe
 * @Date: 2021-03-01
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/control/house")
public class HouseController extends BonorController<House, IHouseService> {
    private String prefix = "control/house";

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IPopulationService populationService;


    /**
     * 首页
     */
    @RequiresPermissions("control:house:view")
    @GetMapping()
    public String index() {
        return prefix + "/house";
    }

    /**
     * 分页列表查询
     *
     * @param house
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "实有房屋信息-分页列表查询")
    @RequiresPermissions("control:house:list")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList(House house,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<House> queryWrapper = QueryGenerator.initQueryWrapper(house, req.getParameterMap());
        Page<House> page = new Page<House>(pageNo, pageSize);
        IPage<House> pageList = houseService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加页面
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") String id, ModelMap map) {
        map.put("base", houseService.getBuilding(id));
        map.put("labelNames", "");
        return prefix + "/add";
    }

    /**
     * 添加
     *
     * @param house
     * @return
     */
    @AutoLog(value = "实有房屋信息-添加")
    @RequiresPermissions("control:house:add")
    @PostMapping(value = "/add")
    @ResponseBody
    public Result<?> add(@Validated House house) {
        house.setInTime(new Date()).setGxsj(new Date());
        houseService.save(house);
        return Result.ok("添加成功！");
    }

    /**
     * 实有房屋详细信息页面
     */
    @GetMapping("/showHouse/{id}")
    public String showHouse(@PathVariable("id") String id, ModelMap map) {
        House house = houseService.getOne(new QueryWrapper<House>().eq("dzbm", id));
        map.put("house", house);
        map.put("labelNames","");
        if(oConvertUtils.isNotEmpty(house.getBq())){
            List<Label> labelList = houseService.getLabel(id);
            StringJoiner joiner = new StringJoiner(",");
            labelList.forEach(item -> joiner.add(item.getLabelName()));
            map.put("labelNames", joiner.toString());
        }
        return "control/infor/house";
    }


    /**
     * 实有房屋详细信息页面 + 实有人口
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, ModelMap map) {
        House house = houseService.getOne(new QueryWrapper<House>().eq("dzbm", id));
        map.put("house", house);
        List<PopulationVo> populations = populationService.listing(new QueryWrapper<Population>().eq("dzbm", id));
        if (populations.size() > 0) map.put("populations", populations);
        map.put("labelNames","");
        if(oConvertUtils.isNotEmpty(house.getBq())){
            List<Label> labelList = houseService.getLabel(id);
            StringJoiner joiner = new StringJoiner(",");
            labelList.forEach(item -> joiner.add(item.getLabelName()));
            map.put("labelNames", joiner.toString());
        }
        return prefix + "/detail";
    }

    /**
     * 实有房屋详细信息页面 + 实有人口
     */
    @GetMapping("/tableDetail/{id}")
    public String tableDetail(@PathVariable("id") String id, ModelMap map) {
        House house = houseService.getOne(new QueryWrapper<House>().eq("dzbm", id));
        map.put("house", house);
        List<PopulationVo> populations = populationService.listing(new QueryWrapper<Population>().eq("dzbm", id));
        if (populations.size() > 0) map.put("populations", populations);
        map.put("labelNames","");
        if(oConvertUtils.isNotEmpty(house.getBq())){
            List<Label> labelList = houseService.getLabel(id);
            StringJoiner joiner = new StringJoiner(",");
            labelList.forEach(item -> joiner.add(item.getLabelName()));
            map.put("labelNames", joiner.toString());
        }
        return prefix + "/tableDetail";
    }


    /**
     * 编辑页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        House house = houseService.getOne(new QueryWrapper<House>().eq("dzbm", id));
        map.put("house", house);
        List<PopulationVo> populations = populationService.listing(new QueryWrapper<Population>().eq("dzbm", id));
        if (populations.size() > 0) map.put("populations", populations);
        map.put("labelNames","");
        if(oConvertUtils.isNotEmpty(house.getBq())){
            List<Label> labelList = houseService.getLabel(id);
            StringJoiner joiner = new StringJoiner(",");
            labelList.forEach(item -> joiner.add(item.getLabelName()));
            map.put("labelNames", joiner.toString());
        }
        return prefix + "/edit";
    }

    /**
     * 编辑
     *
     * @param house
     * @return
     */
    @AutoLog(value = "实有房屋信息-编辑")
    @RequiresPermissions("control:house:edit")
    @PostMapping(value = "/edit")
    @ResponseBody
    public Result<?> edit(@Validated House house) {
        house.setGxsj(new Date());
        if(house.getSfdqjc().equals("N")){
            house.setJczq(0);
        }
        houseService.updateById(house);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "实有房屋信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        houseService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "实有房屋信息-批量删除")
    @RequiresPermissions("control:house:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    @ResponseBody
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.houseService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "实有房屋信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        House house = houseService.getById(id);
        return Result.ok(house);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param house
     */
    @AutoLog(value = "实有房屋信息-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, House house) {
        // Step.1 组装查询条件
        QueryWrapper<House> queryWrapper = QueryGenerator.initQueryWrapper(house, request.getParameterMap());
        // Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<House> pageList = houseService.list(queryWrapper);
        PoliceImportUtil.exportHouseXls(pageList);
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "实有房屋信息");
        mv.addObject(NormalExcelConstants.CLASS, House.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("实有房屋列表数据", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "实有房屋信息-通过excel导入数据")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            try {
                List<House> list = ExcelImportUtil.importExcel(file.getInputStream(), House.class, params);
                long start = System.currentTimeMillis();
                PoliceImportUtil.importHouseSave(list);
                houseService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 模板下载
     *
     * @return
     */
    @AutoLog(value = "实有房屋信息-模板下载", operateType = 6)
    @RequestMapping(value = "/importTemplate")
    public ModelAndView importTemplate() {
        return super.importTemplateXls(House.class, "实有房屋信息");
    }

}
